package com.cloud.sample.controller;

import com.cloud.sample.dto.*;
import com.cloud.sample.entity.User;
import com.cloud.sample.service.UserService;
import com.cloud.common.bean.PageInfo;
import com.cloud.common.bean.ResultInfo;
import com.cloud.common.util.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户接口
 *
 * @author feng
 * @since 2022/05/17
 */
@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据主键ID获取
     *
     * @param id 主键ID
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/get")
    public ResultInfo<UserDTO> get(Integer id) {
        if (id == null) {
            return ResultInfo.badRequest();
        }
        User user = userService.getById(id);
        return ResultInfo.success().setData(ObjectUtils.copy(user, UserDTO.class));
    }
    
    /**
     * 根据条件分页查询
     *
     * @param paramDTO 参数对象
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/query")
    public ResultInfo<PageInfo<UserDTO>> query(@Valid @RequestBody UserQueryParamDTO paramDTO) {
        PageInfo<User> pageInfo = userService.query(paramDTO);
        List<UserDTO> list = ObjectUtils.copy(pageInfo.getRows(), UserDTO.class);
        return ResultInfo.success().setData(pageInfo.build(list));
    }

    /**
     * 新增
     *
     * @param paramDTO 参数对象
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/insert")
    public ResultInfo<String> insert(@Valid @RequestBody UserInsertParamDTO paramDTO) {
        User user = ObjectUtils.copy(paramDTO, User.class);
        userService.save(user);
        return ResultInfo.success();
    }

    /**
     * 更新
     *
     * @param paramDTO 参数对象
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/update")
    public ResultInfo<String> update(@Valid @RequestBody UserUpdateParamDTO paramDTO) {
        User user = ObjectUtils.copy(paramDTO, User.class);
        userService.updateById(user);
        return ResultInfo.success();
    }

    /**
     * 根据主键ID删除
     *
     * @param id 主键ID
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/delete")
    public ResultInfo<String> delete(Integer id) {
        if (id == null) {
            return ResultInfo.badRequest();
        }
        userService.removeById(id);
        return ResultInfo.success();
    }
    
    /**
     * 根据主键ID批量删除
     *
     * @param ids 批量主键ID
     * @return ResultInfo 响应结果
     */
    @PostMapping("/user/batchDelete")
    public ResultInfo<String> batchDelete(@RequestBody List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return ResultInfo.badRequest();
        }
        userService.removeByIds(ids);
        return ResultInfo.success();
    }
}